#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "../comm/log.hpp"
#include "../comm/util.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;
    class Compiler
    {
    public:
        Compiler() = default;
        ~Compiler() = default;
        static bool compile(const std::string& file_name)
        {
              int pid=fork();
              if(pid<0)
              {
                LOG(ERROR) << "内部错误，创建子进程失败" << "\n";
                return false;
              }
              if(pid==0)
              {
                umask(0);
                int stderr_=open(PathUtil::CompileError(file_name).c_str(),O_CREAT|O_WRONLY,0664);
                if(stderr_<0)
                {
                    LOG(WARNING) << "没有成功形成stderr文件" << "\n";
                    exit(1);
                }
                dup2(stderr_,2);
                //程序替换
                execlp("g++", "g++", PathUtil::Src(file_name).c_str(), "-D", "COMPILER_ONLINE","-o", PathUtil::Exe(file_name).c_str(),"-std=c++11" ,nullptr);
                LOG(ERROR) << "启动编译器g++失败，可能是参数错误" << "\n";
                exit(2);
              }
              else
              {
                waitpid(pid,nullptr,0);
                if(FileUtile::IsExist(PathUtil::Exe(file_name)))
                {
                    LOG(INFO) << PathUtil::Src(file_name) << " 编译成功!" << "\n";
                    return true;
                }
                else
                {
                    LOG(ERROR) << "编译失败，没有形成可执行程序" << "\n";
                    return false;
                }
              }
        }
    };


}